import "./index.scss";
import logo from "../../assets/logo.png";

// 导入redux
import { useDispatch } from "react-redux";
import { getUserAPI } from "../../store/modules/user";

// 导入路由
import { useNavigate } from "react-router";

// 导入antd组件
import { Card, Form, Input, Button, message } from "antd";

// 导入声明变量文件
import type { LoginFormItem } from "../../types/login";
import type { AppDispatch } from "../../store/store";

const Login = () => {
  // 创建dispatch实例
  const dispatch = useDispatch<AppDispatch>();
  //   创建路由实例
  const navigator = useNavigate();

  // 表单校验成功回调
  const onFinish = async (values: LoginFormItem) => {
    const key = "login";
    // 调用异步请求Store中的action--登录
    message.loading({ key: key, content: "Login..", duration: 1 });
    await dispatch(getUserAPI(values));
    // 登录成功后跳转
    message.success({ key: key, content: "Login~", duration: 3 });
    setTimeout(() => {
      navigator("/");
    }, 1000);
  };

  return (
    <div className="login">
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        <Form validateTrigger="onBlur" onFinish={onFinish}>
          <Form.Item
            name="mobile"
            // 手机号校验规则
            rules={[
              { required: true, message: "Please input your PhoneNumber!" },
              {
                // 手机号校验规则--正则表达式
                pattern: /^1[0-9]\d{9}$/,
                message: "Please input a valid PhoneNumber!",
              },
            ]}
          >
            <Input
              defaultValue={13800000002}
              size="large"
              placeholder="请输入手机号"
            />
          </Form.Item>
          <Form.Item
            name="code"
            rules={[{ required: true, message: "Please input your Code!" }]}
          >
            <Input
              defaultValue={246810}
              size="large"
              placeholder="请输入验证码"
            />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" size="large" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Login;
